<template>
    <div style="display: flex; gap: 20px; padding: 20px;">
        <!-- 左侧表单 -->
        <div style="flex: 1;">
            <el-form ref="ruleFormRef" :model="formData" :rules="rules" label-width="auto" style="max-width: 600px;">
                <!-- 基础信息 -->
                <h3>基础信息</h3>

                <el-form-item label="开票单号">
                    <div style="display: flex; justify-content: center;">
                        <el-input v-model="formData.invoicingCode" :disabled="autoGenerate" />
                        <el-checkbox v-model="autoGenerate" style="margin-left: 10px;">系统编号</el-checkbox>
                    </div>
                </el-form-item>

                <el-form-item label="开票主体">
                    <el-input v-model="formData.invoicingName" />
                </el-form-item>

                <el-form-item label="发票类型">
                    <el-select style="width: 300px;" v-model="formData.invoicingType" placeholder="" clearable>
                        <el-option label="专用发票" value="专用发票" />
                        <el-option label="普通发票" value="普通发票" />
                        <el-option label="电子发票" value="电子发票" />
                        <el-option label="其他" value="其他" />
                    </el-select>
                </el-form-item>


                <el-form-item label="开票方">
                    <el-select style="width: 300px;" v-model="formData.receiveInvoicing" placeholder="" clearable>
                        <el-option label="白读公司" value="白读公司" />
                        <el-option label="梅团公司" value="梅团公司" />
                        <el-option label="腾旭公司" value="腾旭公司" />
                        <el-option label="景东公司" value="景东公司" />
                    </el-select>
                </el-form-item>

                <el-form-item label="开票时间">
                    <el-date-picker type="date" v-model="formData.invoicingDate"
                        value-format="YYYY-MM-DDTHH:mm:ss.SSSZ" />
                </el-form-item>

                <el-form-item label="备注">
                    <el-input v-model="formData.invoicingDesc" type="textarea" />
                </el-form-item>

                <!-- 订单 -->
                <h3>订单</h3>
                <div style="display: flex; gap: 10px; margin-bottom: 10px;">
                    <el-button type="primary" size="small" @click="showAddOrderDialog = true">添加</el-button>
                    <el-button type="danger" size="small" @click="removeSelectedOrders()">移除</el-button>
                </div>

                <el-table :data="orderdtos" style="width: 100%; min-width: 800px; overflow-x: auto;" border
                    @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column label="序号" width="80">
                        <template #default="{ $index }">
                            {{ $index + 1 }}
                        </template>
                    </el-table-column>
                    <el-table-column label="订单编号" min-width="120">
                        <template #default="{ row }">
                            {{ row.orderCode }}
                        </template>
                    </el-table-column>
                    <el-table-column label="订单数量" min-width="120">
                        <template #default="{ row }">
                            {{ row.orderNum }}
                        </template>
                    </el-table-column>
                    <el-table-column label="订购物品" min-width="150">
                        <template #default="{ row }">
                            {{ row.orderGoods }}
                        </template>
                    </el-table-column>
                    <el-table-column label="总金额" min-width="120">
                        <template #default="{ row }">
                            {{ row.allmomeny }}
                        </template>
                    </el-table-column>
                    <el-table-column label="已付金额" min-width="120">
                        <template #default="{ row }">
                            {{ row.tomomeny }}
                        </template>
                    </el-table-column>
                    <el-table-column label="付款金额" min-width="150">
                        <template #default="{ row }">
                            <el-input v-model="row.invoiceAmount" type="number" size="small" style="width: 100%;" />
                        </template>
                    </el-table-column>
                    <el-table-column label="备注" min-width="150">
                        <template #default="{ row }">
                            <el-input v-model="row.invoicingDesc" size="small" style="width: 100%;" />
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" min-width="200" fixed="right">
                        <template #default="{ $index, row }">
                            <el-button size="small" @click="moveUp($index)">上移</el-button>
                            <el-button size="small" @click="moveDown($index)">下移</el-button>
                            <el-button size="small" type="danger" @click="removeOrder($index)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <div style="text-align: right; margin-top: 20px;">
                    <el-button @click="resetForm(ruleFormRef)">关闭</el-button>
                    <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
                </div>
            </el-form>
        </div>

        <!-- 右侧添加订单弹窗 -->
        <el-dialog title="添加订单" v-model="showAddOrderDialog" width="1000px">
            <el-table :data="availableOrders" @selection-change="handleOrderSelectionChange">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column label="序号" width="60">
                    <template #default="{ $index }">
                        {{ $index + 1 }}
                    </template>
                </el-table-column>
                <el-table-column label="销售订单编号" min-width="120">
                    <template #default="{ row }">
                        {{ row.orderCode }}
                    </template>
                </el-table-column>
                <el-table-column label="下单人" min-width="120">
                    <template #default="{ row }">
                        {{ row.createrPeople }}
                    </template>
                </el-table-column>
                <el-table-column label="订单状态" min-width="120">
                    <template #default="{ row }">
                        {{ getOrderStatus(row.orderState) }}
                    </template>
                </el-table-column>
                <el-table-column label="下单商品" min-width="150">
                    <template #default="{ row }">
                        {{ row.orderGoods }}
                    </template>
                </el-table-column>
                <el-table-column label="订单数量" min-width="120">
                    <template #default="{ row }">
                        {{ row.orderNum }}
                    </template>
                </el-table-column>
            </el-table>

            <div style="margin-top: 20px; text-align: right;">
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="totalOrders"
                    layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"></el-pagination>
            </div>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="showAddOrderDialog = false">取消</el-button>
                    <el-button type="primary" @click="addSelectedOrders">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, watch, onMounted } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'

import axios from 'axios'
import router from '@/router'

// ==================== 接口返回数据类型定义 ====================
interface OrderItem {
    id: number;
    orderCode: string;
    orderSon: string;
    orderState: number;
    orderNum: number;
    orderGoods: string;
    allmomeny: number;
    tomomeny: number;
    clientId: number;
    isOrder: boolean;
    createrPeople: string;
    createTime: Date | string;
    updaterPeople: string;
    updateTime: Date | string;
    isDel: boolean;
    invoicingDesc?: string;
    invoiceAmount?: number | string; // 添加付款金额字段
}

interface OrderResponse {
    totalcount: number;
    totalPage: OrderItem[];
}

// ==================== 表单数据 ====================
const ruleFormRef = ref<FormInstance>()
const formData = reactive({
    invoicingCode: "",
    invoicingName: "",
    invoicingType: "",
    invoicingDate: "",
    invoicingMomeny: "0",
    receiveInvoicing: "",
    invoicingDesc: "",
    createrPeople: "admin",
    createTime: new Date().toISOString(),
    updaterPeople: "admin",
    updateTime: new Date().toISOString()
})

// 自动生成编号
const autoGenerate = ref(false)
watch(autoGenerate, (val) => {
    if (val) {
        formData.invoicingCode = `IN${Date.now()}${Math.floor(Math.random() * 10000)}`
    } else {
        formData.invoicingCode = ''
    }
})

// 订单列表（已选）
const orderdtos = ref<OrderItem[]>([])
// 添加订单弹窗
const showAddOrderDialog = ref(false)

// 可用订单列表
const availableOrders = ref<OrderItem[]>([])
const totalOrders = ref(0)
const currentPage = ref(1)
const pageSize = ref(5)

const fetchAvailableOrders = () => {
    axios.get<OrderResponse>(`/api/InvoiceTicket/Getorder`, {
        params: {
            Index: currentPage.value,
            size: pageSize.value
        }
    })
        .then(res => {
            availableOrders.value = res.data.totalPage || []
            totalOrders.value = res.data.totalcount
        })
        .catch(err => console.error('获取订单失败:', err))
}

// 事件处理
const selectedOrderIds = ref<number[]>([])
const selectedRows = ref<OrderItem[]>([])

const handleSelectionChange = (selection: OrderItem[]) => {
    selectedOrderIds.value = selection.map(s => s.id)
    selectedRows.value = selection
}

const handleOrderSelectionChange = (selection: OrderItem[]) => {
    selectedOrderIds.value = selection.map(s => s.id)
    selectedRows.value = selection
}

const addSelectedOrders = () => {
    const newOrders = availableOrders.value.filter(order => selectedOrderIds.value.includes(order.id))
    orderdtos.value.push(...newOrders)
    showAddOrderDialog.value = false
    selectedOrderIds.value = []
    selectedRows.value = []
}

const removeOrder = (index: number) => {
    orderdtos.value.splice(index, 1)
}

const moveUp = (index: number) => {
    if (index > 0) {
        const temp = orderdtos.value[index]
        orderdtos.value[index] = orderdtos.value[index - 1]
        orderdtos.value[index - 1] = temp
    }
}

const moveDown = (index: number) => {
    if (index < orderdtos.value.length - 1) {
        const temp = orderdtos.value[index]
        orderdtos.value[index] = orderdtos.value[index + 1]
        orderdtos.value[index + 1] = temp
    }
}

const removeSelectedOrders = () => {
    orderdtos.value = orderdtos.value.filter(order => !selectedOrderIds.value.includes(order.id))
    selectedOrderIds.value = []
    selectedRows.value = []
}

const handleSizeChange = (val: number) => {
    pageSize.value = val
    fetchAvailableOrders()
}

const handleCurrentChange = (val: number) => {
    currentPage.value = val
    fetchAvailableOrders()
}

const getOrderStatus = (status: number): string => {
    switch (status) {
        case 0: return '待处理'
        case 1: return '处理中'
        case 2: return '已完成'
        case 3: return '已取消'
        default: return '未知状态'
    }
}

// 处理多个付款
const processPayments = (orders: OrderItem[]): Promise<void> => {
    // 创建一个Promise数组，每个元素代表一个付款请求
    const paymentPromises = orders.map(order => {
        // 准备付款数据
        const paymentData = {
            invoiceAmount: order.invoiceAmount,
            orderId: order.id
        };

        // 返回一个Promise
        return axios.post('/api/InvoiceTicket/AddInvoicePayment', paymentData)
            .then(response => {
                console.log(`订单 ${order.orderCode} 付款成功，返回数据:`, response.data);
                // 更新本地已付金额数据
                order.tomomeny = Number(order.tomomeny || 0) + Number(order.invoiceAmount);
                return response;
            })
            .catch(err => {
                console.error(`订单 ${order.orderCode} 付款失败:`, err);
                throw new Error(`订单 ${order.orderCode} 付款失败: ${err.message}`);
            });
    });

    // 等待所有付款处理完成
    return Promise.all(paymentPromises)
        .then(() => {
            console.log('所有付款处理完成');
            return;
        });
};

// 表单验证规则
const rules = reactive<FormRules>({
    invoicingCode: [
        { required: true, message: '请输入开票单号', trigger: 'blur' }
    ],
    invoicingName: [
        { required: true, message: '请输入开票主体', trigger: 'blur' }
    ],
    invoicingType: [
        { required: true, message: '请选择发票类型', trigger: 'change' }
    ],
    invoicingMomeny: [
        { required: true, message: '请输入开票金额', trigger: 'blur' }
    ]
})

// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (orderdtos.value.length === 0) {
                ElMessage.warning('请至少添加一个订单')
                return
            }

            // 确保包含原始订单ID，这对中间表很重要
            const payload = {
                invoicingCode: formData.invoicingCode,
                invoicingName: formData.invoicingName,
                invoicingType: formData.invoicingType,
                invoicingDate: formData.invoicingDate,
                invoicingDesc: formData.invoicingDesc,
                invoicingMomeny: formData.invoicingMomeny,
                receiveInvoicing: formData.receiveInvoicing,
                createrPeople: formData.createrPeople,
                createTime: formData.createTime,
                updaterPeople: formData.updaterPeople,
                updateTime: formData.updateTime,

                orderdtos: orderdtos.value.map(order => ({
                    id: order.id, // 确保包含原始订单ID
                    orderCode: order.orderCode,
                    orderSon: order.orderSon,
                    orderState: order.orderState,
                    orderNum: order.orderNum,
                    orderGoods: order.orderGoods,
                    allmomeny: order.allmomeny,
                    tomomeny: order.tomomeny,
                    clientId: order.clientId,
                    isOrder: order.isOrder,
                    createrPeople: order.createrPeople,
                    createTime: order.createTime,
                    updaterPeople: order.updaterPeople,
                    updateTime: order.updateTime,
                    invoicingDesc: order.invoicingDesc || "",
                    // 中间表需要的额外数据
                    orderInvoiceRelation: true
                })),

                // 添加procedures数据，这是后端创建中间表的关键
                procedures: orderdtos.value.map(order => ({
                    Id: order.id, // 使用选择的订单ID
                    orderCode: order.orderCode,
                    OrderSon: order.orderSon || "", // 添加OrderSon字段
                    OrderId: order.id, // 确保OrderId也存在
                    OrderGoods: order.orderGoods || "", // 添加OrderGoods字段
                    orderNum: order.orderNum, // 添加订单数量
                    allmomeny: order.allmomeny, // 添加总金额
                    tomomeny: order.tomomeny, // 添加已付金额
                    CreaterPeople: order.createrPeople || "系统", // 添加创建人
                    createTime: order.createTime || new Date().toISOString(), // 添加创建时间
                    updaterPeople: order.updaterPeople || "系统", // 添加更新人
                    updateTime: order.updateTime || new Date().toISOString() // 添加更新时间
                }))
            }

            // 使用配置好的axios实例
            axios.post('/api/InvoiceTicket/AddInvoice', payload)
                .then(response => {
                    console.log('提交成功，返回数据:', response.data)

                    // 检查是否有需要付款的订单
                    const ordersToProcess = orderdtos.value.filter(o => o.invoiceAmount && Number(o.invoiceAmount) > 0);

                    if (ordersToProcess.length > 0) {
                        // 处理付款
                        processPayments(ordersToProcess)
                            .then(() => {
                                ElMessage.success('保存和付款处理完成')
                                resetForm(formEl)
                                orderdtos.value = []
                            })
                            .catch(payError => {
                                console.error('部分付款处理失败:', payError)
                                ElMessage.warning('数据已保存，但部分付款处理失败')
                            });
                    } else {
                        // 无需付款
                        ElMessage.success('创建成功')
                        resetForm(formEl)
                        orderdtos.value = []
                    }
                })
                .catch(err => {
                    console.error('提交失败，错误信息:', err)
                    if (err.response?.status === 404) {
                        ElMessage.error('接口不存在，请检查后端服务或路径')
                    } else if (err.response?.status === 400) {
                        ElMessage.error('请求参数错误，请检查数据格式')
                    } else {
                        ElMessage.error(`创建失败: ${err.response?.data?.message || err.message}`)
                    }
                })
        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (formEl) {
        formEl.resetFields()
    }
    router.push({ path: "/order" })
}

// 页面挂载时初始化
onMounted(() => {
    fetchAvailableOrders()
})
</script>

<style scoped>
.dialog-footer {
    text-align: right;
}
</style>
